﻿using System;
using System.Collections.Generic;
using UnityEngine;

public class AudioManager : Singleton<AudioManager>
{
    private AudioSource backgroundAudio = null;
    private float backgroundVolume = 1;

    private GameObject soundsObj;
    private List<AudioSource> soundAudios = new List<AudioSource>();
    private float soundVolume = 1;

    private string clipsPath { get; } = "AudioClips/";

    public AudioManager()
    {
        MonoEvent.Instance.UPDATE += Tick;
    }
    void Tick()
    {
        for (int i = 0; i < soundAudios.Count; i++)
        {
            if (!soundAudios[i].isPlaying)
            {
                GameObject.Destroy(soundAudios[i]);
                soundAudios.RemoveAt(i);
            }
        }
    }

    /// <summary>
    /// Play background music
    /// </summary>
    /// <param name="name"></param>
    public void PlayBackMusic(string name)
    {
        if (backgroundAudio == null)
        {
            GameObject obj = new GameObject("Background Music");
            backgroundAudio = obj.AddComponent<AudioSource>();
        }


        ResourcesManager.Instance.LoadAsync<AudioClip>(clipsPath + name, (clip) =>
        {
            backgroundAudio.clip = clip;
            backgroundAudio.volume = backgroundVolume;
            backgroundAudio.loop = true;
            backgroundAudio.Play();
        });
    }

    public void ChangeBackVolume(float volumn)
    {
        backgroundVolume = volumn;
        if (backgroundAudio != null)
            backgroundAudio.volume = backgroundVolume;
    }

    public void PauseBackMusic()
    {
        if (backgroundAudio != null)
            backgroundAudio.Pause();
    }

    /// <summary>
    /// Stop background music
    /// </summary>
    public void StopBackMusic()
    {
        if (backgroundAudio != null)
            backgroundAudio.Stop();
    }

    public void PlaySound(string name, bool isLoop, Action<AudioSource> callBack = null)
    {
        if (soundsObj == null)
        {
            soundsObj = new GameObject("Sounds");
        }

        AudioSource audioSource = soundsObj.AddComponent<AudioSource>();
        audioSource.clip = ResourcesManager.Instance.Load<AudioClip>(clipsPath + name);
        audioSource.volume = soundVolume;
        audioSource.loop = isLoop;
        audioSource.Play();

        soundAudios.Add(audioSource);

        callBack?.Invoke(audioSource);
    }

    public void ChangeSoundVolume(float volumn)
    {
        soundVolume = volumn;
        foreach (var audio in soundAudios)
        {
            audio.volume = soundVolume;
        }
    }

    public void StopSound(AudioSource audioSource)
    {
        //TODO: 需要结合对象池
        if (soundAudios.Contains(audioSource))
        {
            soundAudios.Remove(audioSource);
            audioSource.Stop();
            GameObject.Destroy(audioSource);
        }
    }

}